package com.woniuxy.controller;

import com.woniuxy.ResponseResult;

import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.URIBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.ws.rs.core.MultivaluedMap;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 控制从网关过来的所有链接
 */
@RestController
@Slf4j
public class AllController {
    @Value("${server.port}")
    private int port;

    @RequestMapping("auth")
    public ResponseResult<Void> anno(String jwt,String url,String parms) throws URISyntaxException {
        //发送http请求到本项目，会经过shiro过滤器
        log.info("url为："+url);
        log.info("jwt为"+jwt);
        log.info("参数为"+parms);
        URI uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(port).setPath(url).build();
        //增加请求头信息
        HttpHeaders headers = new HttpHeaders();
        headers.add("jwt",jwt);
        RestTemplate restTemplate = new RestTemplate();
        //获取获取发送请求
        HttpEntity<MultiValueMap<String, String>> httpEntity = null;
        if (url.contains("adminUser")){
            String[] split = parms.split("&");
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            for (String string : split) {
                System.out.println(string);
                String[] split2 = string.split("=");
                map.add(split2[0], split2[1]);
            }
            httpEntity = new HttpEntity<>(map, headers);
        }else {
            log.info("无参数发送");
            httpEntity = new HttpEntity<>(headers);
        }
        ResponseResult result =null;
        try{
            log.info("发送开始");
            result = restTemplate.postForObject(uri,httpEntity,ResponseResult.class);
            log.info("发送结束");
        }catch (ExpiredJwtException e){
            log.error("jwt过期");
            e.printStackTrace();
        }catch (Exception e){
            log.error("系统错误");
            e.printStackTrace();
        }
        log.info("发送完毕");
        return result;
    }
}
